package com.googlecode.likesql.expression;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import com.googlecode.likesql.constant.SqlConstant;

/**
 * AtExp represents a precompiled expression with pattern and designated parameters.
 * Quest(?) in the pattern is regarded as a parameter. 
 * The value which is set to the parameter is converted by a configured {@link com.googlecode.likesql.converter.Converter Converter} according to its type.
 * 
 * 
 * @author Johny Huang
 * @since 0.1
 * @see {@link com.googlecode.likesql.converter.QuestExpConverter QuestExpConverter}
 */
public class QuestExp {

    /**
     * Pattern for expression
     */
    private String pattern;
	
	/**
	 * Map for parameterIndex/value
	 */
	private Map values;
	
	/**
	 * The maximum index of parameters.
	 */
	private int maxIndex;
	
	private QuestExp(String pattern){
		this.pattern=pattern;
		values=new TreeMap();
	}
	
	/**
	 * Gets a new instance with a pattern.
	 * @param pattern
	 * @return
	 */
	public static QuestExp qt(String pattern){
		return new QuestExp(pattern);
	}
	
	/**
	 * Sets the index of the quest parameter to value. Index starts from 1.
	 * 
	 * @param index
	 * @param value
	 * @return
	 */
	public QuestExp set(int index,Object value){
		if(index<1){
			throw new IllegalArgumentException("index must larger than 0");
		}
		values.put(new Integer(index-1), value);
		maxIndex=Math.max(maxIndex, index);
		return this;
	}
	
	
	/**
	 * Sets the index of the quest parameter to value. Index starts from 1.
	 * 
	 * @param index
	 * @param value
	 * @return
	 */
	public QuestExp set(int index,long value){
		return set(index,new Long(value));
	}
	
	/**
	 * Sets the index of the quest parameter to value. Index starts from 1.
	 * 
	 * @param index
	 * @param value
	 * @return
	 */
	public QuestExp set(int index,double value){
		return set(index,new Double(value));
	}
	
	/**
	 * Sets the index of the quest parameter to value. Index starts from 1.
	 * 
	 * @param index
	 * @param value
	 * @return
	 */
	public QuestExp set(int index,char value){
		return set(index,String.valueOf(value));
	}

	/**
	 * Sets the index of the quest parameter to value. Index starts from 1.
	 * 
	 * @param index
	 * @param value
	 * @return
	 */
	public String getPattern() {
		return pattern;
	}

	/**
	 * Gets the values array.The index of the value equals corresponding  parameter index -1.
	 * 
	 * @return
	 */
	public Object[] getValues() {
		Object[] objs=new Object[maxIndex];
		Arrays.fill(objs, String.valueOf(SqlConstant.CHAR_FOR_REPLACE));
		Iterator it=values.keySet().iterator();
		Integer key=null;
		while(it.hasNext()){
			key=(Integer)it.next();
			objs[key.intValue()]=values.get(key);
		}
		return objs;
	}
}
